#include "socket_recv_buff.h"

const size_t SocketRecvBuff::HEADER_SIZE = 64;
const size_t SocketRecvBuff::FIELD_SIZE  = 16;
const size_t SocketRecvBuff::MAX_BODY_SIZE = 10000;

SocketRecvBuff::SocketRecvBuff(): Buff() {
	oj     = new char[FIELD_SIZE + 10];
	header = new char[HEADER_SIZE + 10];
	body   = new char[MAX_BODY_SIZE + 10];
	
	memset(header, 0, sizeof(char)*(HEADER_SIZE+10));
	memset(body, 0, sizeof(char)*(MAX_BODY_SIZE+10));

	status = 0;
	index  = 0;
	body_length = 0;
	remain = HEADER_SIZE;
}

SocketRecvBuff::~SocketRecvBuff() {
	delete[] oj;
	delete[] header;
	delete[] body;
}

ssize_t SocketRecvBuff::recv_header(int fd) {
	ssize_t tot = 0;
	while (remain > 0) {
		ssize_t n = read(fd, header+index, remain);
		if (n == -1 || n == 0) return n;
		remain -= n;
		tot += n;
		index += n;
	}
	status = 1;
	return tot;
}

ssize_t SocketRecvBuff::recv_body(int fd) {
	ssize_t tot = 0;
	while (remain > 0) {
		ssize_t n = read(fd, body+index, remain);
		if (n == -1 || n == 0) return n;
		remain -= n;
		index += n;
		tot += n;
	}
	status = 3;
	return tot;
}

void SocketRecvBuff::get_oj() {
	for (int i = 0; i < FIELD_SIZE; i++) {
		oj[i] = header[i];
		if (header[i] == '\0') break;
	}
}

void SocketRecvBuff::get_body_length() {
	body_length = 0;
	for (int i = 0; i < FIELD_SIZE; i++) {
		if (header[3*FIELD_SIZE+i] == '\0') break;
		body_length = body_length * 10 + 
					  header[3*FIELD_SIZE+i]-'0';
	}
	// 为接下来接收body初始化
	index = 0;
	remain = body_length;
}

bool SocketRecvBuff::finish_header() {
	return status >= 1;
}

bool SocketRecvBuff::finish_body() {
	return status >= 2;
}
